<?php

namespace App\Listeners;

use App\Events\OrderPaid;
use Illuminate\Support\Facades\Http;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

//  implements ShouldQueue 代表此监听器是异步执行的
class rechargeOrderTask implements ShouldQueue
{
    // Laravel 会默认执行监听器的 handle 方法，触发的事件会作为 handle 方法的参数
    public function handle(OrderPaid $event)
    {
        // 从事件对象中取出对应的订单
        $order = $event->getOrder();

        if($order->is_pay == 1) {
            // 获取套餐id
            $get_package_id = $order->recharge_package_id;

            // 获取运营商id
            $get_company_id = \DB::table('recharge_package')->where('id', $get_package_id)->first()->operator_id;

            // 获取运营商名称
            $get_company = \DB::table('operator')->where('id', $get_company_id)->first()->s_name;

            // 判断充值类型
            $recharge_type = $order->recharge_type;

            // DTAC后充值方式，要传值为 DTAC，不然会返回无法充值
            if($get_company == 'HAPPY' && $recharge_type == 'billpay' )
            {
                $get_company = 'DTAC';
            }

            // 充值话费还是套餐判断
            if($order->is_aop == '0') {
                $company_type = $get_company;
            } else {
                $company_type = $get_company.'-AOP';
            }

            // 话费充值
            $response = Http::asForm()->post('http://if.topupm.com/api/client_api?', [
                'username'          =>  'zhaiyanyan',    //账号
                'password'          =>  'c159753',   //密码
                'type'              =>  $recharge_type,  //mtopup 或 billpay
                'resp_url'          =>  Route('recharge.callback'),  //回调地址: POST 接收充值结果 transaction_id , status , msg_zh
                'pay_to_company'    =>  $company_type,  //运营商参数:12CALL/TRMV/HAPPY/MY
                'pay_to_amount'     =>  finance_format($order->total_amount),  //充值金额
                'pay_to_ref1'       =>  $order->cellphone,  //充值号码
                'dest_ref'          =>  GetRandStr(30)   //随机数:格式a-z，A-Z，0-9，长度30
            ]);

            //查询余额
            // $response_balance = Http::asForm()->post('http://if.topupm.com/api/client_api?', [
            //     'username'          => 'zhaiyanyan',    //账号
            //     'password'          => 'c159753',   //密码
            //     'type'              => 'balance_inquiry'
            // ]);

            $result = json_decode($response->getBody(), true);

            if($result['code'] == '00000') {
                $order->update([
                    'recharge_no'   => $result['transaction_id'],
                    'remark'    =>  '运营商：' . $company_type,
                ]);
            } else {
                //退款
                $apprefund = \EasyWeChat::payment();

                $refund = $apprefund->refund->byTransactionId($order->payment_no, 'TK'.$order->payment_no, $order->real_amount, $order->real_amount, [
                    // 可在此处传入其他参数，详细参数见微信支付文档
                    'refund_desc' => '[' . $result['code'] . ']' . $result['msg'],
                ]);

                // 更新订单状态
                $order->update([
                    'refund_status'     =>  1, //1 已退款
                    'recharge_status'   =>  4, //4 充值失败
                    'refund_no'         =>  'TK'.$order->payment_no,
                    'remark'            =>  '运营商：' . $company_type,
                    'recharge_extra'    =>  '[' . $result['code'] . ']' . $result['msg']
                ]);
            }

        }
    }
}
